package com.lecoboy.highconcurrency.connectionDemo.thread_pool_demo;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 手写线程池测试类
 */
public class ThreadPoolTest {


    public static void main(String[] args) throws InterruptedException {

        for (int j = 0; j < 50; j++) {

            AtomicInteger count = new AtomicInteger();
            //定义线程池数 可根据改变线程池数来看执行效率
            ThreadPool threadPool = new DefaultThreadPool(4);
            //计数器

            for (int i = 0; i < 20000; i++) {
                //执行job
                threadPool.execute(new MyJob(count));
            }
            threadPool.getExecteResult();

            System.out.println(j + "实际执行:" + count.get());
            System.out.println();
            TimeUnit.SECONDS.sleep(4);
        }
    }

    /**
     * 实际执行线程
     */
    static class MyJob implements Runnable {

        AtomicInteger count;

        MyJob(AtomicInteger count) {
            this.count = count;
        }

        @Override
        public void run() {
            //count.incrementAndGet();
            safeCount(count);
        }
    }
    private static void safeCount(AtomicInteger count){
        for (;;){
            int i=count.get();
            boolean suc = count.compareAndSet(i,++i);
            if(suc){
                break;
            }
        }
    }
}
